<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" v-if="isShow">
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入编号" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
          <a-form-model-item label="关联客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
            <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"  @change="kehuChange" :disabled='isAdd'/>
          </a-form-model-item>
          </a-col>
          <a-col :span="24" >
            <a-form-model-item label="关联合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderContractId">
              <relatecontract displayKey="number" v-model="model.orderContractId" :query-config="hetongConfig" :multiple="true" :url="hetongurl" v-if="customerIdShow" @change="hetongChange" :disabled='isAdd'></relatecontract>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联应收款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivablesIds">
              <receivables displayKey="number" v-model="model.receivablesIds" :query-config="yingshoukuanConfig" :multiple="true" :url="yingshoukuanurl" v-if="orderIdShow" @change="yingshoukuanChange" disabled></receivables>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="回款金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collectionAmount">
              <a-input-number v-model="model.collectionAmount" placeholder="请输入回款金额" style="width: 100%"  :disabled='isHK'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='only' >
            <a-form-model-item label="回款明细" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collectionDetailsList" >
              <a-table bordered
                       :dataSource="dataSource"
                       :columns="columnsAmount"
                       :pagination="false"
                       :scroll="{x:true}"
                       rowKey="id">
                <template slot="number" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="yskNumber" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="collectionAmounts" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="operation" slot-scope="text, record,index">
                  <a @click="AmountEdit(record)" :disabled='isAdd'>编辑</a>
                </template>
              </a-table>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="归属人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="owner">
              <j-select-user-by-dep v-model="model.owner" :multi="true" :disabled='isAdd' />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="回款日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collectionDate">
              <j-date placeholder="请选择回款日期" v-model="model.collectionDate"  style="width: 100%" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="收款账户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collectionAccount">
              <j-dict-select-tag type="list" v-model="model.collectionAccount" dictCode="collection_account" placeholder="请选择收款账户" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="支付方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentMethod">
              <j-dict-select-tag type="list" v-model="model.paymentMethod" dictCode="collection_payment_method" placeholder="请选择支付方式" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remrak">
              <a-input v-model="model.remrak" placeholder="请输入备注"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="files">
              <j-upload v-model="model.files"   ></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" :disabled='isAdd' />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <AmountInfoModal ref="AmountInfo" @ok="AmountEditOK"></AmountInfoModal>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import EditableCell from '@/components/EditableCellPay/cell'
  import relatecontract from '@/components/jeecgbiz/relatecontract/index'
  import receivables from '@/components/jeecgbiz/receivables/index'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
  import JSelectMultiUser from '@comp/jeecgbiz/JSelectMultiUserCustom'
  import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom'
  import JSelectUserByDepCustom from '@comp/jeecgbiz/JSelectUserByDepCustom'
  import JSelectBizComponentModal from '@/components/jeecgbiz/relatecontract/JSelectBizComponentModal'
  import AmountInfoModal from '@views/payment/modules/AmountInfoModal'
  import moment from 'moment'
  export default {
    name: 'PaymentCollectionForm',
    components: {
      JSelectUserByDep,
      relatecontract,
      receivables,
      JSelectMultiUser,
      JSelectUserByDepCustom,
      JSelectUserByDepModalCustom,
      JSelectBizComponentModal,
      EditableCell,
      AmountInfoModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      'model.customerId': {
        deep: true,
        handler(newValue, oldValue) {
          if (!newValue || newValue !== oldValue) {
            this.customerIdShow = false
          }
          if (newValue) {
            this.$nextTick(() => {
              this.customerIdShow = true
              this.kehuurl = '/customer/customer/lists?filed=2&id=' + newValue
              if (this.model.orderContractId) {
                this.hetongurl = '/contractorder/contractOrder/lists?customerId=' + newValue + '&id=' + this.model.orderContractId

              }
              else {
                this.hetongurl = '/contractorder/contractOrder/lists?customerId=' + newValue
              }
            })
          }
        }
      },
      'model.orderContractId': {
        deep: true,
        handler(newValue, oldValue) {
          if (!newValue || newValue !== oldValue) {
            this.orderIdShow = false
          }
          if (newValue) {
            this.$nextTick(() => {
              this.orderIdShow = true
              this.yingshoukuanurl = '/receivables/receivables/lists?id=' + newValue
              // this.yingshoukuanurl = '/sys/common/queryByReceivables?id=' + newValue
            })
          }
        }
      },
      'model.collectionAmount': {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          console.log('collectionAmount的变化', newValue)
        }
      },
      dataSource: {
        deep: true,
        immediate: true,
        handler(newValue, oldValue) {
          console.log('dataSource的变化', newValue)
          this.TotalAmount()
        }
      },
    },
    data () {
      return {
        CountKey:1,
        isHK:true,//回款金额是否可编辑
        isAdd:false,//添加/编辑显示字段
        only:false,//回款明细是否显示
        htNumber:'',
        yskNumber:'',
        receId:'',
        htNumbers:'',
        collectionAmounts:0,
        receivablesIds:'',
        orderContractId:'',
        customerIdShow: false,
        orderIdShow: false,
        isShow:false,
        dataSource: [],//回款金额临时数组
        kehuurl:'/customer/customer/lists?filed=2',
        // 选择用户查询条件配置
        selectUserQueryConfig: [
          {key: 'phone', label: '电话'},
        ],
        hetongurl: '/contractorder/contractOrder/list?filed=2'+'&customerId=',
        hetongConfig: [
          { key: 'number', label: '合同编号' }
        ],
        yingshoukuanurl:'/sys/common/queryByReceivables?id=',
        yingshoukuanConfig: [
          {key: 'number', label: '应收款编号'},
        ],
        //金额表格配置
        columnsAmount: [
          {
            title:'合同编号',
            dataIndex: 'htNumber',
            width: 200,
            key: 'orderContractId',
            scopedSlots: { customRender: 'orderContractId' }
          },
          {
            title:'应收款编号',
            dataIndex: 'yskNumber',
            width: 200,
            key: 'receivablesIds',
            scopedSlots: { customRender: 'receivablesIds' }
          },
          {
            title:'回款金额',
            dataIndex: 'collectionAmounts',
            width: 100,
            key: 'collectionAmounts',
            scopedSlots: { customRender: 'collectionAmounts' }
          },
          {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            fixed: 'right',
            width: 120,
            scopedSlots: { customRender: 'operation' }
          }
        ],
        model:{
          collectionAmounts:0,
          collectionAmount:0,
          collectionAccount:1,
          collectionDate: '',
          receivablesIds:'',

        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          number: [
              { required: true, message: '请输入编号!'},
           ],
          customerId: [
            { required: true, message: '请选择关联客户!'},
          ],
          orderContractId: [
            { required: true, message: '请选择关联合同!'},
          ],
          collectionAmount: [
            { required: true, message: '请输入回款金额!'},
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          owner: [
            { required: true, message: '请选择归属人!'},
          ],
          collectionDate: [
            { required: true, message: '请选择回款日期!'},
          ],
          collectionAccount: [
            { required: true, message: '请选择收款账户!'},
          ],
          directorIds: [
            { required: true, message: '请选择负责人!'},
          ],
        },
        url: {
          add: "/payment/paymentCollection/add",
          edit: "/payment/paymentCollection/edit",
          queryById: "/payment/paymentCollection/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      moment,
      kehuChange(e) {
        console.log('客户按钮后',e)
        this.customerIdShow = false
        this.model.contactsIds = ''
      },
      hetongChange(e) {
        this.orderIdShow = false
        this.model.receivablesIds = ''
        console.log('合同按钮后',e)
        let orderContractId = e
        //根据合同id查询合同 只有一个合同id的时候
        if(orderContractId.length == 1){
        getAction('/contractorder/contractOrder/queryById?id='+ orderContractId ).then(res => {
            if (res.success) {
              let htTempArr = res.result
              console.log('查询到的合同htTempArr',htTempArr)
              //根据合同id查询应收款
              getAction('/sys/common/queryByReceivables?id='+ orderContractId ).then(res => {
                if (res.success) {
                  let yskTempArr = res.result
                  console.log('查询到的应收款yskTempArr',yskTempArr)
                  //没有应收款时显示合同金额中的未收金额
                  if(yskTempArr.length == 0){
                    this.only = false
                    this.isHK = false
                    let AmountArr = htTempArr.map(e =>{
                      return e.uncollectedAmount
                    })
                    this.model.collectionAmount = AmountArr.toString()
                    let newArr = [ ]
                    htTempArr.forEach((item)=>{
                      newArr.push({
                        htNumber:item.number,
                        collectionAmounts:item.uncollectedAmount,
                        contractOrderId:item.id,
                      });
                    })
                    this.dataSource = newArr
                  }else if(yskTempArr.length == 1 ){//有一条应收款时显示一条应收款的值
                    this.only = false
                    this.isHK = false
                    //从数组中取出应收金额
                    let AmountArr = yskTempArr.map(e =>{
                      return e.uncollectedAmount
                    })
                    this.model.collectionAmount = AmountArr.toString()
                    //从数组中取出id
                    let idArr = yskTempArr.map(e =>{
                      return e.id
                    })
                    this.model.receivablesIds = idArr.toString()
                    let newArr = [ ];
                    yskTempArr.forEach((e)=>{
                      let TempArr = e
                      getAction('/contractorder/contractOrder/queryById?id='+ orderContractId).then(res => {
                        if (res.success) {
                          let htTempArr = res.result
                          let htNumArr = htTempArr.map(e =>{
                            return e.number
                          })
                          let htNum = htNumArr.toString()
                          console.log('htNum',htNum)
                          TempArr.htNum = htNum
                          console.log('TempArr',TempArr)
                          newArr.push({
                            receId:e.id,
                            yskNumber:e.number,
                            collectionAmounts:e.uncollectedAmount,
                            contractOrderId:e.orderContractId,
                            htNumber:e.htNum
                          });
                        }
                      })

                    })
                    this.dataSource = newArr
                  }else{//多条应收款时显示回款明细
                    this.only = true
                    this.isHK = true
                    //从数组中取出id
                    let idArr = yskTempArr.map(e =>{
                      return e.id
                    })
                    this.model.receivablesIds = idArr.toString()
                    let newArr = [ ];
                    yskTempArr.forEach((e)=>{
                      let TempArr = e
                        getAction('/contractorder/contractOrder/queryById?id='+ orderContractId).then(res => {
                          if (res.success) {
                            let htTempArr = res.result
                            let htNumArr = htTempArr.map(e =>{
                              return e.number
                            })
                            let htNum = htNumArr.toString()
                            console.log('htNum',htNum)
                            TempArr.htNum = htNum
                            console.log('TempArr',TempArr)
                            newArr.push({
                              receId:e.id,
                              yskNumber:e.number,
                              collectionAmounts:e.uncollectedAmount,
                              contractOrderId:e.orderContractId,
                              htNumber:e.htNum
                            });
                          }
                        })
                    })
                    this.dataSource = newArr
                    this.TotalAmount()
                  }
                }else{
                  this.$message.warning(res.message);
                }
              })
            }else{
              this.$message.warning(res.message);
            }
        })
        }else{
          //多个合同id的时候
          getAction('/contractorder/contractOrder/queryById?id='+ orderContractId ).then(res => {
            if (res.success) {
              let htTempArr = res.result
              console.log('查询到的合同htTempArr',htTempArr)
              //根据合同id查询应收款
              getAction('/sys/common/queryByReceivables?id='+ orderContractId ).then(res => {
                if (res.success) {
                  let yskTempArr = res.result
                  console.log('查询到的应收款yskTempArr',yskTempArr)
                  //没有应收款时显示合同金额
                  if(yskTempArr.length == 0){
                    this.only = true
                    this.isHK = true
                    let newArr = [];
                    htTempArr.forEach((item)=>{
                      newArr.push({
                        // receId:item.receivablesIds,
                        htNumber:item.number,
                        collectionAmounts:item.uncollectedAmount,
                        contractOrderId:item.id,
                        key:this.CountKey
                      });
                      this.CountKey+=1
                    })
                    this.dataSource = newArr
                    this.TotalAmount()
                  }
                  else {//多条应收款时显示回款明细
                    this.only = true
                    this.isHK = true
                    let yskId = yskTempArr.map(e =>{
                      return e.id
                    })
                    this.model.receivablesIds = yskId.toString()
                    //遍历应收款中的合同id
                    let yskhtIdArr = yskTempArr.map(e =>{
                      return e.orderContractId
                    })
                    let yskhtId = Array.from(new Set(yskhtIdArr));//应收款中的合同id去重
                    // console.log('去重后',yskhtId)
                    //遍历选中的合同id
                    let htIdArr = htTempArr.map(e =>{
                      return e.id
                    })
                    //两个id数组做比较
                    let flag =  true
                    let newArr = [];
                    htIdArr.forEach(item => {
                        if (yskhtId.indexOf(item) === -1){//合同没有应收款的合同id
                          flag = false
                          let bczId = item
                          console.log('falseeeeeeeeeeeeeeeeee',bczId)
                          //如果合同数组id中包含item 则push数据
                          htTempArr.forEach(item => {
                            if (bczId.includes(item.id)){
                              newArr.push({
                                htNumber:item.number,
                                collectionAmounts:item.uncollectedAmount,
                                contractOrderId:item.id,
                                key:this.CountKey
                              });
                              this.CountKey+=1
                            }
                          })
                        }else{//合同有应收款的合同id
                          flag = true
                          let czId  = [ ]
                          czId = item
                          console.log('trueeeeeeeeeeeeeeeeeeee',czId)
                          //判断ysk中htid是否和czid相等
                          yskTempArr.forEach((e)=>{
                            let TempArr = e
                            if ( e.orderContractId == czId ){
                              getAction('/contractorder/contractOrder/queryById?id='+ czId ).then(res => {
                                if (res.success) {
                                  let htTempArr = res.result
                                  let htNumArr = htTempArr.map(e =>{
                                    return e.number
                                  })
                                  let htNum = htNumArr.toString()
                                  console.log('htNum',htNum)
                                  TempArr.htNum = htNum
                                  console.log('TempArr',TempArr)
                                  newArr.push({
                                    receId:e.id,
                                    yskNumber:e.number,
                                    collectionAmounts:e.uncollectedAmount,
                                    contractOrderId:e.orderContractId,
                                    htNumber:e.htNum,
                                    key:this.CountKey
                                  });
                                  this.CountKey+=1
                                }
                              })
                            }
                          })
                        }
                      this.dataSource = newArr
                      this.TotalAmount()
                      })
                  }
                }else{
                  this.$message.warning(res.message);
                }
              })
            }else{
              this.$message.warning(res.message);
            }
          })
        }
      },
      //回款金额总和
      TotalAmount(){
        let all = 0
        this.dataSource.forEach(res => {
          all += Number(res.collectionAmounts)
        })
        this.model.collectionAmount = all
        console.log('回款金额总和',this.model.collectionAmount)
      },
      //金额编辑
      AmountEdit(record) {
        this.$refs.AmountInfo.edit(record)
      },
      AmountEditOK(res) {
        console.log('添加应收款返回数据', res)
        const { CountKey, dataSource } = this
        if (res.key) {
          //编辑的情况
          const dataSource = [...this.dataSource]
          let target = dataSource.find((item) => item.key == res.key)
          target = Object.assign(target, res)
          this.dataSource = dataSource
        }
        this.TotalAmount()
      },
      yingshoukuanChange(e) {
        console.log(e)
      },
      add () {
        this.edit(this.modelDefault);
        this.isShow= false
        this.isAdd = false
        this.model.collectionDate = this.moment().format('YYYY-MM-DD')
      },
      // 获取回款明细表格
      getYskInfo(){
        getAction(this.url.queryById,{id:this.model.id}).then(res=>{
          console.log("获取回款明细",res)
          let dataTemp = res.result
          let dataArr = dataTemp.collectionDetailsList
          let htId = dataArr.map(e=>{
            return  e.contractOrderId
          })
          let orderContractId = htId.toString()
          let newArr = [ ]
          dataArr.forEach(e=>{
             e.receId
            if( e.receId == null){//应收款id为空的时候
              getAction('/contractorder/contractOrder/queryById?id='+ e.contractOrderId ).then(res => {
                if (res.success) {
                  let htTempArr = res.result
                  console.log('查询到的htTempArr',htTempArr)
                  let collectionAmounts = e.collectionAmounts
                  htTempArr.forEach(item=>{
                    newArr.push({
                      htNumber:item.number,
                      collectionAmounts:collectionAmounts,
                    })
                  })
                  this.dataSource = newArr
                }
              })
            } else{//应收款不为空的时候
              getAction('/receivables/receivables/queryById?id='+ e.receId ).then(res => {
                if(res.success){
                  let yskTempArr = res.result
                  let yskArr = Array( yskTempArr)
                  console.log('查询到的应收款yskArr',yskArr)
                  let yskId = yskArr.map(e=>{
                    return e.id
                  })
                  let receivablesIds = yskId.toString()
                  console.log('receivablesIdssssssssssss',receivablesIds)
                  let htId = yskArr.map(e=>{
                    return e.orderContractId
                  })
                  let orderContractId = htId.toString()
                    getAction('/contractorder/contractOrder/queryById?id='+ orderContractId ).then(res => {
                    if (res.success) {
                      let htTempArr = res.result
                      console.log('查询到的htTempArr',htTempArr)
                      let htNumber = htTempArr.map(e=>{
                       return  e.number
                      })
                      this.htNumbers = htNumber.toString()
                      console.log('this.htNumbers',this.htNumbers)
                      let collectionAmounts = e.collectionAmounts
                      yskArr.forEach(item=>{
                        newArr.push({
                          yskNumber: item.number,
                          htNumber:this.htNumbers,
                          collectionAmounts:collectionAmounts,
                        })
                      })
                      this.dataSource = newArr
                      console.log('dataSourceeeeeeeeeeeeeeee',this.dataSource)
                    }
                  })
                }
              })
            }
          })
        })
      },
      edit (record) {
        this.isAdd = true
        this.isShow= true
        this.only = true
        this.model = Object.assign({}, record);
        this.getYskInfo()
        this.visible = true;
      },
      submitForm () {
        this.model.collectionDetailsList = this.dataSource
        console.log('this.model', this.model)
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
    }
  }
</script>